﻿using System;
using System.Data;

namespace zijian666.Data
{
    /// <summary>
    /// 用于在 <see cref="IDbConnection"/> 上创建一个作用域，作用域结束时自动关闭连接。
    /// </summary>
    internal class OpenScope : IDisposable
    {
        private readonly bool _isOpen;
        private IDbConnection _connection;

        public OpenScope(IDbConnection connection)
        {
            _isOpen = connection.OpenIfClosed();
            _connection = connection;
        }

        public void Dispose()
        {
            if (_isOpen)
            {
                _connection?.SafeClose();
            }
            _connection = null;
        }
    }
}
